package com.server.repository;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import com.server.base.ConstantCommon;
import com.server.model.QueryIndex;
import com.server.model.elasticsearch.PartyIndexInfo;

public interface PartyIndexInfoRepository extends ElasticsearchRepository<PartyIndexInfo, Long> {

	public static class Query {
		public static SearchQuery dynamicSearch(QueryIndex queryIndex) {
			NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
					.withSearchType(SearchType.DFS_QUERY_THEN_FETCH).withIndices("hudongba_innodb")
					.withTypes("PARTY_SHOW");
			List<Sort.Order> orders = new ArrayList<Sort.Order>();
			BoolFilterBuilder booleanFilter = FilterBuilders.boolFilter();
			Boolean hasFilter = Boolean.FALSE;
			if (queryIndex.getAreaId() == -1) {
				orders.add(new Sort.Order(Sort.Direction.DESC, "isRecommendAll"));
			}else {
				orders.add(new Sort.Order(Sort.Direction.DESC, "isRecommendArea"));
			}
			if (queryIndex.getCategoryId() != -1) {
				orders.add(new Sort.Order(Sort.Direction.ASC, "sortByArea"));
				booleanFilter.must(FilterBuilders.queryFilter(QueryBuilders.matchPhraseQuery("catIds",
						queryIndex.getCategoryId())));
				hasFilter = Boolean.TRUE;
			}
			orders.add(new Sort.Order(Sort.Direction.DESC, "labelTime"));
			Sort sort = new Sort(orders);
			Pageable pageables = new PageRequest(queryIndex.getPageIndex(), ConstantCommon.DEFAULT_PC_PAGE_SIZE, sort);
			nativeSearchQueryBuilder.withPageable(pageables);
			if (queryIndex.getIsCharged() != -1) {
				booleanFilter.must(FilterBuilders.termFilter("isCharge", queryIndex.getIsCharged()));
				hasFilter = Boolean.TRUE;
			}
			if (queryIndex.getAreaId() != -1) {
				booleanFilter.must(FilterBuilders.termFilter("areaId2", queryIndex.getAreaId()));
				hasFilter = Boolean.TRUE;
			}
			if (queryIndex.getRemark() != -1) {
				booleanFilter.must(FilterBuilders.rangeFilter("infoStartDate").gte(queryIndex.getStartDate())
						.lte(queryIndex.getEndDate()));
				hasFilter = Boolean.TRUE;
			}
			if (hasFilter) {
				nativeSearchQueryBuilder.withFilter(booleanFilter);
			}
			return nativeSearchQueryBuilder.build();
		}

	}

}
